package com.fagp.mew.cms.controller.permission;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fagp.mew.cms.messages.PageRequest;
import com.fagp.mew.cms.messages.PageResponse;
import com.mew.common.dc.mapper.PermissionMapper;
import com.mew.common.dc.mapper.RoleMapper;
import com.mew.common.entity.back.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RolesAllowed({"ADMIN"})
@RequestMapping("/perm")
public class PermController {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @ResponseBody
    @RequestMapping("/all")
    public PageResponse all(PageRequest p){
        List<Permission> perms = permissionMapper.selectList(new QueryWrapper<>());
        //父权限
        Map<Integer, Permission> map = perms.stream().filter(i -> i.getMenu() == null).collect(Collectors.toMap(Permission::getId, i -> i));
        //子权限
        perms.stream().filter(i -> i.getMenu() != null).forEach(i->{
            Permission parent = map.get(i.getMenu());
            i.setMenuName(parent.getName());
            parent.getChildren().add(i);
        });

        //转list
        List<Permission> permissions = map.values().stream().collect(Collectors.toList());
        //排序
        Collections.sort(permissions,(p1,p2)->{return p1.getId().compareTo(p2.getId());});
        //整合
        ArrayList<Permission> res = new ArrayList<>();
        for (Permission value : permissions) {
            res.add(value);
            res.addAll(value.getChildren());
        }

        return new PageResponse(res);
    }

}
